package com.cheng.dataStructure.stack;

import java.util.Scanner;

/**
 * @User Administrator
 * @Classname ArrayStackDemo01
 * @Project Data-structure-and-algorithm
 * @Description 实现栈的思路分析
 * 1. 使用数组来模栈
 * 2. 使用top变量来表示栈顶，初始化为-1
 * 3. 入栈：top++，stack[top]=data；
 * 4. 出栈：int value=stack[top],top--,return value
 * @Author wpcheng
 * @Create 2021-07-19-9:00
 * @Version 1.0
 */
public class ArrayStackDemo01 {
    public static void main(String[] args) {
        ArrayStack stack = new ArrayStack(5);
        String key = "";
        boolean loop = true;//控制是否退出菜单
        Scanner scanner = new Scanner(System.in);
        while(loop){
            System.out.println("show：显示栈");
            System.out.println("exit：退出程序");
            System.out.println("push：添加数据");
            System.out.println("pop：取出数据");
            System.out.println("要执行的操作：");
            key = scanner.next();
            switch (key) {
                case "show":
                    stack.list();
                    break;
                case "push":
                    System.out.println("请输入一个数");
                    int value = scanner.nextInt();
                    stack.push(value);
                    break;
                case "pop":

                    int res = 0;
                    try {
                        res = stack.pop();
                        System.out.printf("出栈的数据是%d\n",res);
                    } catch (Exception e) {
                        System.out.println(e.getMessage());;
                    }
                    break;
                case "exit":
                    scanner.close();
                    loop = false;
                    break;
                default:
                    break;
            }
        }
        System.out.println("程序退出");

    }
}

//定义一个栈
class ArrayStack{
    private int maxSize; //栈的大小
    private int[] stack; //数组
    private int top = -1; //栈顶，初始化为-1

    public ArrayStack(int maxSize){
        this.maxSize = maxSize;
        stack = new int[maxSize];// 初始化栈的大小为maxSize
    }

    //栈满
    public boolean isFull(){
        return top == maxSize - 1;
    }
    //栈空
    public boolean isEmpty(){
        return top == -1;
    }
    //入栈
    public void push(int value){
        if (isFull()){
            System.out.println("栈满，无法添加");
            return;
        }
        top++;
        stack[top] = value;//把value放入栈中
    }
    //出栈
    public int pop(){
        if (isEmpty()){
            throw new RuntimeException("栈空，无法取出");
        }
        int value = stack[top];//从栈顶取出数据放入value中
        top--;
        return value;
    }
    //显示栈
    public void list(){
        if (isEmpty()){
            System.out.println("栈空");
            return;
        }
        //从栈顶开始遍历
        for (int i = top; i >= 0 ; i--) {
            System.out.printf("stack[%d]=%d\n" , i, stack[i]);
        }
    }

}
